<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('员工姓名')" prop="staffName">
            <UserSelect v-model="form.staffName" :placeholder="$t('员工姓名')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('员工部门')" prop="departmentId">
            <tree-select v-model="form.departmentId" node-key="id" disabled :default-expand-all="true" :data="deptOptions" :placeholder="$t('请选择')">
              <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('现任职位')" prop="postId">
            <el-select v-model="form.postId" disabled>
              <el-option
                v-for="(item) in hrPositions"
                :key="item.id"
                :label="$t(item.postName)"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('身份证号码')" prop="idCard">
            <el-input v-model="form.idCard" :placeholder="$t('身份证号码')" show-word-limit maxlength="32" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div class="area-header" style="margin-top: 15px">
            <span class="area-header-title">{{ $t('本人及/或本人配偶、子女和父母是否存在以本人名义、以化名或借用他人名义开立的、可以用于股票交易的证券账户（包括中国内地及内地以外证券账户）?') }}</span>
          </div>
          <el-form-item prop="bondAccountExist">
            <el-radio-group v-model="form.bondAccountExist">
              <el-radio-button
                v-for="dict in bondAccountExistOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <!--本人及/或本人配偶、子女和父母是否存在以本人名义、以化名或借用他人名义开立的、可以用于股票交易的证券账户（包括中国内地及内地以外证券账户）?-->
      <div v-if="form.bondAccountExist === 'Y'">
        <el-table :data="form.riskFamilyAccountList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('姓名')" align="center" min-width="160">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('姓名') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'riskFamilyAccountList.' + scope.$index + '.name'" :rules="riskFamilyAccountListRules.name">
                <el-select v-model="scope.row.name" @change="getFamilyDetail(scope.$index, form.riskFamilyAccountList, scope.row.name)">
                  <el-option
                    v-for="item in nameOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('亲属关系')" align="center" show-overflow-tooltip min-width="160">
            <template slot-scope="scope">
              <el-form-item :prop="'riskFamilyAccountList.' + scope.$index + '.relationship'">
                <el-select v-model="scope.row.relationship">
                  <el-option
                    v-for="dict in relationshipOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('身份证号码')" align="center" show-overflow-tooltip min-width="160">
            <template slot-scope="scope">
              <el-form-item :prop="'riskFamilyAccountList.' + scope.$index + '.idCard'">
                <el-input v-model="scope.row.idCard" :placeholder="$t('身份证号码')" maxlength="32" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('证券账户')" align="center" show-overflow-tooltip min-width="160">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('证券账户') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'riskFamilyAccountList.' + scope.$index + '.boundAccount'" :rules="riskFamilyAccountListRules.boundAccount">
                <el-input v-model="scope.row.boundAccount" :placeholder="$t('证券账户')" maxlength="32" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['risk:bondAccountRegister:remove']" type="text" icon="el-icon-delete" @click="delFamilyAccountHandle(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addriskFamilyAccountList">{{ $t('添加') }}</el-button>
        </div>
      </div>
      <div style="margin-top: 15px">
        <!--持仓明细填报-->
        <div class="area-header">
          <span class="area-header-title">{{ $t('持仓明细填报') }}</span>
        </div>
        <el-table :data="form.riskPositionDetailList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('姓名')" align="center" min-width="160">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('姓名') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'riskPositionDetailList.' + scope.$index + '.name'" :rules="riskPositionDetailListRules.name">
                <el-select v-model="scope.row.name">
                  <el-option
                    v-for="item in nameOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('持有证券类型')" align="center" show-overflow-tooltip min-width="160">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('持有证券类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'riskPositionDetailList.' + scope.$index + '.holdBoundType'" :rules="riskPositionDetailListRules.holdBoundType">
                <el-select v-model="scope.row.holdBoundType">
                  <el-option
                    v-for="dict in holdBoundTypeOptions"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('持有证券代码')" align="center" show-overflow-tooltip min-width="160">
            <template slot-scope="scope">
              <el-form-item :prop="'riskPositionDetailList.' + scope.$index + '.holdBoundCode'">
                <el-input v-model="scope.row.holdBoundCode" :placeholder="$t('持有证券代码')" maxlength="32" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('持有证券名称')" align="center" show-overflow-tooltip min-width="160">
            <template slot-scope="scope">
              <el-form-item :prop="'riskPositionDetailList.' + scope.$index + '.holdBoundName'">
                <el-input v-model="scope.row.holdBoundName" :placeholder="$t('持有证券名称')" maxlength="32" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('数量')" align="center" show-overflow-tooltip min-width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'riskPositionDetailList.' + scope.$index + '.number'">
                <Money v-model="scope.row.number" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('查询结果所属日期')" align="center" show-overflow-tooltip min-width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'riskPositionDetailList.' + scope.$index + '.queryResultDate'">
                <DatePicker v-model="scope.row.queryResultDate" :placeholder="$t('查询结果所属日期')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('市值') + $t('金额单位')" align="center" show-overflow-tooltip min-width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'riskPositionDetailList.' + scope.$index + '.marketValue'">
                <Money v-model="scope.row.marketValue" unit="w" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" min-width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['risk:bondAccountRegister:remove']" type="text" icon="el-icon-delete" @click="delPositionDetailHandle(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addriskPositionDetailList">{{ $t('添加') }}</el-button>
        </div>
      </div>
      <div style="margin-top: 15px">
        <!--声明与承诺-->
        <div class="area-header">
          <span class="area-header-title">{{ $t('声明与承诺') }}</span>
        </div>
        <p>{{ $t('1. 本人承诺上述登记内容真实、准确、完整，不存在任何虚假记载、误导性陈述或者重大遗漏；如上述登记内容发生变更，本人将主动并及时进行补充披露。') }}</p>
        <p>{{ $t('2. 本人承诺遵守所有适用的法律和监管要求，以及公司的政策和制度，不会从事内幕交易、利益冲突行为等任何违法违规、违反公司规章制度的行为。') }}</p>
        <p>{{ $t('3. 公司应相关监管机构要求，或在公司认为必要且合理的情况下，本人同意配合公司联系开立账户的金融机构以获取关于本人及利害关系人证券交易状况的信息。') }}</p>
        <el-form-item prop="oneselfSure">
          <template>
            <el-checkbox :key="true" v-model="form.oneselfSure">{{ $t('本人确认上述声明与承诺') }}</el-checkbox>
          </template>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="risk:bondAccountRegister" />
    </div>
  </div>
</template>

<script>
import { saveRiskBondAccountRegister, getRiskBondAccountRegister, listUserName } from '@/api/deal/risk/bondAccountRegister/riskBondAccountRegister'
    import { listPost } from '@/api/system/post'
    import { treeselect } from '@/api/system/dept'
    import { getUser } from '@/api/system/user'
    import TreeSelect from '@/components/TreeSelect/index'
    import { delRiskFamilyAccount } from '@/api/deal/risk/familyAccount/riskFamilyAccount'
    import { delRiskPositionDetail } from '@/api/deal/risk/positionDetail/riskPositionDetail'
    import { getRiskFamilyMembers } from '@/api/deal/risk/familyMembers/riskFamilyMembers'
    import { getRelatedParties } from '@/api/deal/risk/relatedParties/riskRelatedParties'
    export default {
      components: {
        TreeSelect
      },
        data() {
            return {
                // 表单参数
                form: {
                  riskFamilyAccountList: [],
                  riskPositionDetailList: []
                },
                // 部门
                deptOptions: [],
                // 职位
                hrPositions: [],
                // 姓名
                nameOptions: [],
                // 是否
                bondAccountExistOptions: [],
                // 持有证券类型
                holdBoundTypeOptions: [],
                // 亲属关系
                relationshipOptions: [],
                // 选择的用户昵称
                currentUserName: '',
                // 遮罩层
                loading: false,
                // 是否隐藏其它按钮
                otherBtnHide: false,
                // 表单校验
                rules: {
                  staffName: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  departmentId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  idCard: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  oneselfSure: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }, { validator: this.checkOneselfSure, trigger: 'blur' }]
                },
                // 本人及/或本人配偶、子女和父母是否存在以本人名义、以化名或借用他人名义开立的、可以用于股票交易的证券账户（包括中国内地及内地以外证券账户）表单校验
                riskFamilyAccountListRules: {
                  name: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  relationship: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  idCard: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                // 本人及/或本人配偶、子女和父母是否存在以本人名义、以化名或借用他人名义开立的、可以用于股票交易的证券账户（包括中国内地及内地以外证券账户）表单校验
                riskPositionDetailListRules: {
                  name: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  holdBoundType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                // 查询公司指标参数
                queryParams: {
                  staffName: undefined
                }
            }
        },
      watch: {
        'form.staffName': {
          handler(val) {
            if (val !== undefined && val !== null && val !== '') {
              this.userInfo(val)
            }
          },
          deep: true,
          immediate: true
        }
      },
        created() {
          // 系统是否
          this.getDicts('sys_yes_no').then(response => {
            this.bondAccountExistOptions = response.data
          })
          // 持有证券类型
          this.getDicts('hold_bound_type').then(response => {
            this.holdBoundTypeOptions = response.data
          })
          // 部门
          treeselect().then(response => {
            this.deptOptions = response.data
          })
          // 职位
          listPost({}).then(response => {
            this.hrPositions = response.rows
          })
          // 与本人关系
          this.getDicts('relation_ship').then(response => {
            this.relationshipOptions = response.data
          })
        },
        methods: {
            // 初始化数据
            init(data) {
              this.loading = true
              if (data != null && data.id !== undefined) {
                    getRiskBondAccountRegister(data.id).then(response => {
                      this.form = response.data
                      if (this.form.oneselfSure === 'true') {
                        this.form.oneselfSure = true
                      }
                      this.$set(this.form, 'postId', response.data.postId)
                      this.loading = false
                    })
                } else {
                    this.reset()
                    this.form.staffName = this.$store.state.user.userId
                    this.userInfo(this.form.staffName)
                    this.loading = false
                }
            },
            // 根据选择的用户不同显示部门和岗位
            userInfo(userId) {
              getUser(userId).then(response => {
                this.form.departmentId = response.data.deptId
                this.currentUserName = response.data.nickName
                this.form.postId = response.datas.postIds[0]
              })
              // 获取所有关联项目
              this.queryParams.staffName = userId
              listUserName(this.queryParams).then(response => {
                this.nameOptions = response.rows
              })
            },
            // 回显数据
            getFamilyDetail(index, data, name) {
              var lableName = ''
              this.nameOptions.forEach(item => {
                if (item.id === name) {
                  lableName = item.label
                }
              })
              // 选择的是员工回显
              if (this.currentUserName === lableName) {
                getRelatedParties(name).then(response => {
                  this.form.riskFamilyAccountList[index].relationship = 'BR'
                  this.form.riskFamilyAccountList[index].idCard = response.data.idCard
                })
              } else {
                // 选择的是家属回显
                getRiskFamilyMembers(name).then(response => {
                  this.form.riskFamilyAccountList[index].relationship = response.data.relationship
                  this.form.riskFamilyAccountList[index].idCard = response.data.idCard
                })
              }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    staffName: undefined,
                    postId: undefined,
                    departmentId: undefined,
                    idCard: undefined,
                    bondAccountExist: 'N',
                    oneselfSure: false,
                    remark: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined,
                    riskFamilyAccountList: [],
                    riskPositionDetailList: []
                }
                this.resetForm('form')
            },
          // 添加关系密切家庭成员基本情况
          addriskFamilyAccountList() {
            const row = {
              id: undefined,
              bondAccountId: '',
              name: '',
              relationship: '',
              idCard: '',
              boundAccount: '',
              remark: ''
            }
            if (!(this.form.riskFamilyAccountList instanceof Array)) {
              this.$set(this.form, 'riskFamilyAccountList', [])
            }
            this.$nextTick(() => {
              this.form.riskFamilyAccountList.push(row)
            })
          },
          // 删除关系密切家庭成员基本情况
          delFamilyAccountHandle(index, row) {
            // eslint-disable-next-line no-undef
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return delRiskFamilyAccount(id)
                }).then(() => {
                this.form.riskFamilyAccountList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.riskFamilyAccountList.splice(index, 1)
            }
          },
          // 添加关系密切家庭成员基本情况
          addriskPositionDetailList() {
            const row = {
              id: undefined,
              bondAccountId: '',
              name: '',
              holdBoundType: '',
              holdBoundCode: '',
              holdBoundName: '',
              number: '',
              queryResultDate: '',
              marketValue: '',
              remark: ''
            }
            if (!(this.form.riskPositionDetailList instanceof Array)) {
              this.$set(this.form, 'riskPositionDetailList', [])
            }
            this.$nextTick(() => {
              this.form.riskPositionDetailList.push(row)
            })
          },
          // 删除关系密切家庭成员基本情况
          delPositionDetailHandle(index, row) {
            // eslint-disable-next-line no-undef
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return delRiskPositionDetail(id)
                }).then(() => {
                this.form.riskPositionDetailList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.riskPositionDetailList.splice(index, 1)
            }
          },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveRiskBondAccountRegister(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                       this.locationError(document)
                    }
                })
           },
          // 校验oneselfSure是否勾选
           checkOneselfSure(rule, value, callback) {
            if (value) {
              callback()
            } else {
              callback(new Error(this.$t('必填信息')))
            }
          }

        }

    }
</script>
